import forEach from "lodash/forEach";

import { createApp, App } from "../../app";

import { GLOBAL_APP_CLS } from "../../variable";

// components
import { AUIDropdown } from "../../../ui/dropdown/dropdown.component";
AUIDropdown.install();

import { AUIDropdownItem } from "../../../ui/dropdown/dropdown-item.component";
AUIDropdownItem.install();

import { AuiDate } from "../../../ui/date/date.component";
AuiDate.install();

import { AuiYear } from "../../../ui/date/year.component";
AuiYear.install();

import { AuiMonth } from "../../../ui/date/month.component";
AuiMonth.install();

import { AuiDatepicker } from "../../../ui/date/datepicker.component";
AuiDatepicker.install();

import { AUISelect } from "../../../ui/form/select.component";
AUISelect.install();

import { AUILoading } from "../../../ui/loading/loading";
AUILoading.install();

import { AUIPagiantion } from "../../../ui/pagination/pagination";
AUIPagiantion.install();

import { deleteToken } from "../../token";

import { TOKEN_IS_EXPIRED_CODE, SERVER_TOKEN_FAILED_CODE } from "../../error";

// modules
const BaseModule =  () => ({
    component: import('./base/index')
});

const BaseIndexModule =  () => ({
    component: import('./base_index/index')
});

const BaseVariableModule =  () => ({
    component: import('./base_variable/index')
});

const UIModule =  () => ({
    component: import('./ui/index')
});

const UIIndexModule =  () => ({
    component: import('./ui_index/index')
});

const UILayoutModule =  () => ({
    component: import('./ui_layout/index')
});

const UIIconModule =  () => ({
    component: import('./ui_icon/index')
});

const UIButtonModule =  () => ({
    component: import('./ui_button/index')
});

const FormModule =  () => ({
    component: import('./form/index')
});

const FormIndexModule =  () => ({
    component: import('./form_index/index')
});

const FormDateModule =  () => ({
    component: import('./form_date/index')
});

let routes = [
    // otherwise  当所有都不存在的时候  会找这个
    { path: '/', redirect: '/base' },
    {
        path: "/base",
        title: "Base",
        component: BaseModule,
        children: [
            {
                path: '',
                name: "项目",
                component: BaseIndexModule
            },
            {
                path: 'variable',
                name: "变量",
                component: BaseVariableModule
            },
        ]
    },
    {
        path: "/ui",
        title: "UI",
        component: UIModule,
        children: [
            {
                path: '',
                name: "颜色",
                component: UIIndexModule
            },
            {
                path: 'layout',
                name: "布局",
                component: UILayoutModule
            },
            {
                path: 'icon',
                name: "图标",
                component: UIIconModule
            },
            {
                path: 'button',
                name: "按钮",
                component: UIButtonModule
            },
        ]
    },
    {
        path: "/form",
        title: "Form",
        component: FormModule,
        children: [
            {
                path: '',
                name: "base",
                component: FormIndexModule
            },
            {
                path: 'date',
                name: "date",
                component: FormDateModule
            },
        ]
    },
];

function handleChildenRoute(parent, routes, level) {
    var ret = [];
    ret = routes.map(function (route, index) {
        route.parent = parent;
        route.level = level;
        route.meta = {
            parent: parent
        };
        route.beforeEnter = (to, from, next) => {
            next();
        };
        return route;
    });
    return ret;
}

// 处理路由 得到当前主路由位置
var lastActiveIndex = 0;
routes = routes.map(function (v, index) {
    v.active = false;
    v.level = 1;
    v.meta = {
        root: v
    };
    v.beforeEnter = (to, from, next) => {
        next();
    };
    if (v.children) {
        v.children = handleChildenRoute(v, v.children, v.level + 1);
    }
    return v;
});


import initRouter from "./router";
const router = initRouter(VueRouter, routes, {});

class DemoApp extends App {
    constructor() {
        super("苏州开心盒子");
        this.router = router;
        this.methods = {
            appToogleMenu() {
                this.$el.classList.toggle(GLOBAL_APP_CLS + "--menu-opened");
            },
            appMenuIsOpen() {
                return this.$el.classList.contains(GLOBAL_APP_CLS + "--menu-opened");
            },
            appToogleAside() {
                this.appClass[GLOBAL_APP_CLS + "--pad"] = !this.appClass[GLOBAL_APP_CLS + "--pad"]
            },
            appIsAside() {
                return this.appClass[GLOBAL_APP_CLS + "--pad"];
            },
            goLoginPage() {
                // console.log("need login");
                window.location.href = `http://home.console.aunbox.cn.dev/?callback_path=${location.host}&callback_hash=${location.hash.replace("#", "")}#/access/signin`;
            },
            onError(error) {
                var self = this;
                window.globalNotfy.alert("系统错误 " + error.code + " " + error.message);
                            
                setTimeout(() => {
                    if (error.code == TOKEN_IS_EXPIRED_CODE) {
                        console.log("token 失效");
                        self.goLoginPage();
                    }
    
                    if (error.code == SERVER_TOKEN_FAILED_CODE) {
                        console.log("token 失效");
                        self.goLoginPage();
                    }
                }, 700);
            },
            loginout() {
                deleteToken();
                this.goLoginPage();
            }
        };
    }
    _nav() {
        var self = this;
        return `
            <div class="aui-display-inline-block kx-app__brand"><span>${self._title}</span></div><button 
            class="aui-button aui-hidden-gt-sm kx-app__nav-toggle"
                @click="appToogleMenu"
            ><i class="fa fa-bars" aria-hidden="true"></i></button>
            <button 
            class="aui-button aui-hidden-lt-md kx-app__aside-toggle"
                @click="appToogleAside"
            ><i class="fa fa-fw fa-dedent" aria-hidden="true"></i></button>
            <div class="kx-app__nav-actions">                
                <div class="kx-app__nav-action kx-app__nav-drop">
                    <aui-dropdown class="aui-dropdown--default" ref="dropdown">
                        <template>
                            andy <i class="aui-caret"></i>                            
                        </template>                        
                        <template slot="menu">
                             <div class="aui-dropdown-item" @click="loginout">退出</div>
                        </template>                       
                    </aui-dropdown>                                   
                </div>                             
            </div>
        `
    }
    _data() {
        var ret = {};

        ret.appClass = {};

        ret.appClass[GLOBAL_APP_CLS + "--pad"] = true;

        ret.selectValue = "";

        ret.routes = routes;
        ret.lastActiveIndex = lastActiveIndex;

        ret.menus = routes.filter(function (v) {
            return v.path !== "/";
        });

        ret.projectmenus = [
            {
                active: false,
                icon: "icon-crm",
                title: "DEMO-演示项目",
                path: ""
            },
        ];
        return ret;
    }
    _mounted() {
        var self = this;

        var currentTooltip = {};
        forEach(self.$refs.projectmenus.getMenus(), function (projectmenu) {
            projectmenu.addEventListener("mouseenter", function () {
                currentTooltip = new window.AUITooltip(projectmenu, {
                    placement: 'right',
                    title: projectmenu.getAttribute("data-title"),
                });
                currentTooltip.show();
            });
            projectmenu.addEventListener("mouseleave", function () {
                currentTooltip.dispose();
            });
        })

        window.globalNotfy = new window.AUINotyf();
    }
}

export var appInstance = createApp(DemoApp);